package com.iman.manjusri.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.math.NumberUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.util.Assert;

import com.iman.common.Constants;
import com.iman.common.util.ConfigUtil;
import com.iman.common.util.MD5;
import com.iman.manjusri.Web7Constants;
import com.iman.manjusri.domain.User;

public abstract class Web7Util {
    private static Properties   jdbcProperties;
    private static final String jdbcPropsFile = "/jdbc.properties"; // 配置文件路径

    public static final String getFileSeparator() {
        return System.getProperty("file.separator");
    }

    public static Properties getContextProperties() {
        if (null == jdbcProperties) {
            jdbcProperties = new Properties();
            try {
                InputStream is = Web7Util.class.getResourceAsStream(jdbcPropsFile);
                jdbcProperties.load(is);
                is.close();
            } catch (IOException ex) {
                System.out.println("装载文件--->失败!");
                ex.printStackTrace();
            }
        }
        return jdbcProperties;
    };

    // 设置当前登录的用户
    public static final void setCurrentUser(User user) {
        Subject currentUser = SecurityUtils.getSubject();
        if (null != currentUser) {
            Session session = currentUser.getSession();
            if (null != session) {
                session.setAttribute(Constants.CURRENT_LOGINUSER_KEY, user);
            }
        }
    };

    // 设置当前登录的用户
    public static final void setCurrentUser(User user,HttpServletRequest request) {
        Subject currentUser = SecurityUtils.getSubject();
        if (null != currentUser) {
            Session session = currentUser.getSession();
            if (null != session) {
                session.setAttribute(Constants.CURRENT_LOGINUSER_KEY, user);
            }
            
            if(request!=null){
            	request.getSession().setAttribute(Constants.CURRENT_LOGINUSER_KEY, user);
            }
        }
    };

    
    // 获取当前登录的用户
    //TODO change it 
    public static final User getCurrentUser() {
       /* User user = new User();
        user.setUserId("1");
        return user;*/
        		Subject currentUser = SecurityUtils.getSubject();
        		if (null != currentUser) {
        			Session session = currentUser.getSession();
        			if (null != session) {
        			User user = (User) session.getAttribute(Constants.CURRENT_LOGINUSER_KEY);
        				if (null != user) {
        					return user;
        				}
        			}
        		}
        		return null;
    };

    //获取当前登录的用户 
    public static final Session getSession() {
        Subject currentUser = SecurityUtils.getSubject();
        return currentUser.getSession();
    };

    public static void print(HttpServletResponse response, String s) {
        try {
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().print(s);
            response.getWriter().flush();
            //response.getWriter().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    };

   
 

    
    //获取当前用户，并判断是否是 老师
    public static final boolean isTeacheUser() {
        User user = getCurrentUser();
        return false;
    }

    //用户是否被审批通过，就是交钱没。
    public static final boolean isApproved(User user) {
        Assert.notNull(user);
        return  false;
    }

    //用户是否被审批通过，就是交钱没。
    public static final boolean isApproved() {
        User user = getCurrentUser();
        return isApproved(user);
    }

    /**
     * 
     *  Function:
     *  功能说明：
     *	 使用说明：
     *  @author  wangxiaolei  DateTime 2014年12月17日 下午12:13:00
     *	返回类型: void    
     *  @param response
     *  @param uidKey
     */
    public static void setUserIdCookie(/*Cookie cookie ,*/HttpServletResponse response,String uidKey){
    	Cookie  cookie  = new Cookie(Web7Constants.SHARECOOKIEUSERID,uidKey);
		String cookie_path   = ConfigUtil.getString("cookie.path");
		String cookie_domain = ConfigUtil.getString("cookie.domain");
		String cookie_times  = ConfigUtil.getString("cookie.times");
		//设置说明		 
		cookie.setComment("shared sessoin id");
		//设置存放的域名
		cookie.setDomain( cookie_domain );
		//设置超时时间  秒
		cookie.setMaxAge(NumberUtils.toInt(cookie_times, 60*60*24*2) );
		//设置cookie 路径
		cookie.setPath(cookie_path);
		//设置cookie版本
		cookie.setVersion(1);
		//增加cookie
		response.addCookie(cookie);
		
		//吧uid这个key 再次md5 2次去钱是为 ，放入cookie 作为验证私钥 
		setUserIdCookiePrivateKey(response,   MD5.digest(MD5.digest(uidKey))   );
    	
    }
    
    /**
     * 写入 uid的 private 作为辅助验证
     * @param response
     * @param uidKey
     */
    public static void setUserIdCookiePrivateKey(/*Cookie cookie ,*/HttpServletResponse response,String uidKey){
    	Cookie  cookie  = new Cookie(Web7Constants.SHARECOOKIEUSERID_PRIVATEKEY,uidKey);
		String cookie_path   = ConfigUtil.getString("cookie.path");
		String cookie_domain = ConfigUtil.getString("cookie.domain");
		String cookie_times  = ConfigUtil.getString("cookie.times");
		//设置说明		 
		cookie.setComment("shared sessoin id PK");
		//设置存放的域名
		cookie.setDomain( cookie_domain );
		//设置超时时间  秒
		cookie.setMaxAge(NumberUtils.toInt(cookie_times, 60*60*24*2) );
		//设置cookie 路径
		cookie.setPath(cookie_path);
		//设置cookie版本
		cookie.setVersion(1);
		//增加cookie
		response.addCookie(cookie);
    	
    }
    
    /**
     * 
     *  Function:
     *  功能说明： 验证    用户的cookie是否正确
     *	 使用说明：
     *  @author  wangxiaolei  DateTime 2014年12月17日 下午12:16:02
     *	返回类型: boolean    
     *  @param uid
     *  @param uidKey
     *  @return
     */
    public static boolean checkCookieIdIsOk(String uid,String uidKey){
    	 if(uidKey!=null &&  uidKey.equals(  MD5.digest(MD5.digest(uid))   )){
    		 return true;
    	 }else{
    		 return false;
    	 }
    	
    }
    
    /**
     * 
     *  Function:
     *  功能说明：获取登陆的 信息 cookie   获取session有关的ID
     *	 使用说明：
     *  @author  wangxiaolei  DateTime 2014年12月16日 下午5:45:22
     *	返回类型: Map<String,String>    
     *  @param request
     *  @param uidKey
     *  @return   uid:value   ,  uidpk:value
     */
    public static Map<String,String> getUId (/*Cookie cookie ,*/HttpServletRequest request ){
    	Map<String,String>  cookieSessionKey = new HashMap<String,String>();
        Cookie[] cookies = request.getCookies();  
        for(Cookie c :cookies ){  
            if(  Web7Constants.SHARECOOKIEUSERID.equals(  c.getName()) ||  Web7Constants.SHARECOOKIEUSERID_PRIVATEKEY.equals(  c.getName()) ){
            	cookieSessionKey.put(c.getName(), c.getValue());
            }
        }  
        return cookieSessionKey;
    }
    
    
	
	/**
	 * 
	 *  Function:
	 *  功能说明： 推出登陆的时候   消除session
	 *	 使用说明：
	 *  @author  wangxiaolei  DateTime 2014年12月16日 下午6:05:54
	 *	返回类型: void    
	 *  @param request
	 *  @param response
	 *  @param uidKey
	 */
    public static void removeCookie(/*Cookie cookie ,*/HttpServletRequest request,HttpServletResponse response ){
        Cookie[] cookies = request.getCookies();  
        String cookie_path   = ConfigUtil.getString("cookie.path");
		String cookie_domain = ConfigUtil.getString("cookie.domain");
		if(cookies!=null){
			 for(Cookie c :cookies ){  
		            c = new Cookie(c.getName(), null);  
		            c.setDomain(cookie_domain);  
		            c.setPath(cookie_path);  
		            c.setMaxAge(0);  
		            response.addCookie(c);  
		        } 
		}
        
    }
}
